from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Dict, Any, List, Optional
from datetime import datetime, timedelta
import os
import json

from app.api import deps
from app.core.payment_logger import payment_logger
from app.services.payment_manager import payment_manager
from app.services.payment_base import PaymentProvider

router = APIRouter()

@router.get("/debug/logs")
async def get_payment_logs(
    hours: int = Query(24, description="获取最近几小时的日志"),
    level: str = Query("INFO", description="日志级别过滤"),
    provider: Optional[str] = Query(None, description="支付提供商过滤"),
    order_id: Optional[str] = Query(None, description="订单ID过滤"),
    current_user = Depends(deps.get_current_user_optional)
):
    """获取支付系统日志（需要管理员权限）"""
    
    # 这里可以添加管理员权限检查
    # if not current_user or not current_user.is_superuser:
    #     raise HTTPException(status_code=403, detail="需要管理员权限")
    
    try:
        log_file_path = "logs/payment.log"
        if not os.path.exists(log_file_path):
            return {"logs": [], "message": "日志文件不存在"}
        
        # 读取日志文件
        with open(log_file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # 过滤日志
        filtered_logs = []
        cutoff_time = datetime.now() - timedelta(hours=hours)
        
        for line in lines[-1000:]:  # 只读取最后1000行
            if not line.strip():
                continue
                
            # 简单的时间过滤（可以改进）
            if level.upper() in line:
                if provider is None or provider in line:
                    if order_id is None or order_id in line:
                        filtered_logs.append(line.strip())
        
        return {
            "logs": filtered_logs[-100:],  # 返回最新100条
            "total": len(filtered_logs),
            "filters": {
                "hours": hours,
                "level": level,
                "provider": provider,
                "order_id": order_id
            }
        }
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取日志失败: {str(e)}")

@router.get("/debug/service-status")
async def get_service_debug_status():
    """获取详细的支付服务状态"""
    
    status = {}
    
    for provider, service in payment_manager.get_all_services().items():
        try:
            service_status = {
                "provider": provider.value,
                "available": True,
                "supported_methods": [method.value for method in service.get_supported_methods()],
                "config_status": _check_service_config(service),
                "last_test_result": None  # 可以添加健康检查结果
            }
        except Exception as e:
            service_status = {
                "provider": provider.value,
                "available": False,
                "error": str(e),
                "supported_methods": [],
                "config_status": {},
                "last_test_result": None
            }
        
        status[provider.value] = service_status
    
    return status

@router.post("/debug/test-payment/{provider}")
async def test_payment_connection(
    provider: str,
    test_data: Dict[str, Any] = None,
    current_user = Depends(deps.get_current_user_optional)
):
    """测试支付服务连接（需要管理员权限）"""
    
    # 这里可以添加管理员权限检查
    
    try:
        payment_provider = PaymentProvider(provider)
        service = payment_manager.get_service(payment_provider)
        
        if not service:
            raise HTTPException(status_code=404, detail=f"支付服务 {provider} 不存在")
        
        # 执行基本的服务测试
        test_results = {
            "provider": provider,
            "timestamp": datetime.now().isoformat(),
            "tests": []
        }
        
        # 测试1: 配置检查
        config_test = {
            "name": "配置检查",
            "status": "success",
            "details": _check_service_config(service)
        }
        test_results["tests"].append(config_test)
        
        # 测试2: 支持的方法
        methods_test = {
            "name": "支持的支付方法",
            "status": "success",
            "details": {
                "methods": [method.value for method in service.get_supported_methods()]
            }
        }
        test_results["tests"].append(methods_test)
        
        # 记录测试日志
        payment_logger.log_payment_event(
            payment_logger.PaymentEventType.SERVICE_ERROR,  # 使用此类型表示测试
            payment_logger.PaymentLogLevel.INFO,
            f"执行支付服务测试",
            provider=provider,
            extra_data=test_results
        )
        
        return test_results
        
    except ValueError:
        raise HTTPException(status_code=400, detail=f"不支持的支付提供商: {provider}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"测试失败: {str(e)}")

@router.get("/debug/orders/{order_id}")
async def debug_order_status(
    order_id: str,
    provider: Optional[str] = None,
    current_user = Depends(deps.get_current_user)
):
    """调试订单状态（获取详细信息）"""
    
    try:
        results = {}
        
        # 如果指定了provider，只查询该提供商
        if provider:
            try:
                payment_provider = PaymentProvider(provider)
                service = payment_manager.get_service(payment_provider)
                if service:
                    result = await service.query_payment(order_id)
                    results[provider] = {
                        "status": "success",
                        "data": result.__dict__ if result else None
                    }
                else:
                    results[provider] = {"status": "service_not_available"}
            except Exception as e:
                results[provider] = {"status": "error", "message": str(e)}
        else:
            # 查询所有支付提供商
            for payment_provider, service in payment_manager.get_all_services().items():
                try:
                    result = await service.query_payment(order_id)
                    results[payment_provider.value] = {
                        "status": "success",
                        "data": result.__dict__ if result else None
                    }
                except Exception as e:
                    results[payment_provider.value] = {
                        "status": "error", 
                        "message": str(e)
                    }
        
        # 记录查询日志
        payment_logger.log_payment_event(
            payment_logger.PaymentEventType.ORDER_QUERY,
            payment_logger.PaymentLogLevel.INFO,
            f"调试查询订单状态",
            order_id=order_id,
            extra_data=results
        )
        
        return {
            "order_id": order_id,
            "query_results": results,
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"调试查询失败: {str(e)}")

@router.post("/debug/simulate-callback/{provider}")
async def simulate_payment_callback(
    provider: str,
    callback_data: Dict[str, Any],
    current_user = Depends(deps.get_current_user_optional)
):
    """模拟支付回调（用于测试）"""
    
    # 这里可以添加管理员权限检查
    
    try:
        payment_provider = PaymentProvider(provider)
        service = payment_manager.get_service(payment_provider)
        
        if not service:
            raise HTTPException(status_code=404, detail=f"支付服务 {provider} 不存在")
        
        # 记录模拟回调
        payment_logger.log_payment_event(
            payment_logger.PaymentEventType.ORDER_CALLBACK,
            payment_logger.PaymentLogLevel.INFO,
            f"模拟支付回调",
            order_id=callback_data.get("order_id", "unknown"),
            provider=provider,
            extra_data={"simulated": True, "callback_data": callback_data}
        )
        
        # 处理回调
        result = await service.handle_notification(callback_data)
        
        return {
            "provider": provider,
            "callback_data": callback_data,
            "processing_result": result.__dict__ if result else None,
            "timestamp": datetime.now().isoformat()
        }
        
    except ValueError:
        raise HTTPException(status_code=400, detail=f"不支持的支付提供商: {provider}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"模拟回调失败: {str(e)}")

def _check_service_config(service) -> Dict[str, Any]:
    """检查服务配置状态"""
    config_status = {}
    
    # 这里可以添加具体的配置检查逻辑
    # 例如检查必要的配置项是否存在
    config = service.config if hasattr(service, 'config') else {}
    
    required_fields = []
    if hasattr(service, 'app_id'):
        required_fields.extend(['app_id'])
    if hasattr(service, 'mch_id'):
        required_fields.extend(['mch_id'])
    if hasattr(service, 'api_key'):
        required_fields.extend(['api_key'])
    
    for field in required_fields:
        value = getattr(service, field, None)
        config_status[field] = {
            "configured": value is not None and value != "",
            "masked_value": "***" if value else None
        }
    
    return config_status